package org.tinygroup.dbclustercase.algorithm;

import java.util.Collection;
import java.util.LinkedHashSet;

import org.tinygroup.dbcluster.algorithm.database.SingleKeyDatabaseShardingAlgorithm;
import org.tinygroup.dbcluster.base.ShardingValue;

public class SingleKeyModuloDatabaseShardingAlgorithm implements
		SingleKeyDatabaseShardingAlgorithm<String> {

	public String doEqualSharding(
			final Collection<String> availableTargetNames,
			final ShardingValue<String> shardingValue) {
		String value = shardingValue.getValue();
		int shardValue = Integer.valueOf(getShardValue(value));
		for (String each : availableTargetNames) {
			if (each.endsWith(shardValue % 2 + "")) {
				return each;
			}
		}
		throw new UnsupportedOperationException();
	}

	public Collection<String> doInSharding(
			final Collection<String> availableTargetNames,
			final ShardingValue<String> shardingValue) {
		Collection<String> result = new LinkedHashSet<String>(
				availableTargetNames.size());
		Collection<String> values = shardingValue.getValues();
		for (String value : values) {
			int shardValue = Integer.valueOf(getShardValue(value));
			for (String dataSourceName : availableTargetNames) {
				if (dataSourceName.endsWith(shardValue % 2 + "")) {
					result.add(dataSourceName);
				}
			}
		}
		return result;
	}

	public static String getShardValue(String value) {
		int length = value.length();
		return value.substring(length - 3, length - 1);
	}

	public Collection<String> doBetweenSharding(
			final Collection<String> availableTargetNames,
			final ShardingValue<String> shardingValue) {
		return availableTargetNames;
	}
}